import re
import json

from flask import Blueprint, render_template, request
from Config.Config import get_redis_client

useLinear = Blueprint('useLinear', __name__)


@useLinear.route('/Linear', methods=['POST'])
def Linear():
    # 请求体中获取参数
    featureColumns = request.form.get('featureColumns')
    if featureColumns is not None:
        # print(featureColumns)
        featureColumnsList = re.findall(r'"(.*?)"', featureColumns)
        featureColumnsList = [fc.strip('"') for fc in featureColumnsList]
        featureColumnsList = list(enumerate(featureColumnsList))
        featureColumns = [item[1] for item in featureColumnsList]
        # print({type(featureColumns)})
        # print(featureColumns)
    else:
        print("featureColumns无参数")

    featureColumn = request.form.get('featureColumn')
    if featureColumn is not None:
        print("featureColumn参数:", featureColumn)
    else:
        print("featureColumn无参数")

    test_size_user = request.form.get('testSizeUser')
    if test_size_user is not None:
        # 只有当 test_size_user_str 不是 None 时才尝试转换为 float
        test_size_user = float(test_size_user)
    else:
        # 当 test_size_user 不存在或为空时，可以设置一个默认值或者抛出异常
        print("test_size_user设置为默认值")
        test_size_user = 0.3  # 设置一个默认值
    # print("test_size_user:", test_size_user)

    random_state_user = request.form.get('randomStateUser')
    if random_state_user is not None:
        random_state_user = int(random_state_user)
    else:
        print("random_state_user设置为默认值")
        random_state_user = 42  # 设置一个默认值
    # print("random_state_user:", random_state_user)

    train_file = request.form.get('trainFile')
    test_file = request.form.get('testFile')
    # 将参数存储到Redis中
    key = "regressionShare"
    params = {
        'featureColumns': featureColumns,
        'featureColumn': featureColumn,
        'test_size_user': test_size_user,
        'random_state_user': random_state_user,
        'train_file':  train_file,
        'test_file': test_file,
        }
    redis_client = get_redis_client()
    redis_client.set(key, json.dumps(params))

    return "参数已传递"
